<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  //ElTag,
  ElMessageBox,
  ElLoading,
  ElTabs
} from 'element-plus'

import { Table } from '@/components/Table'
import { ucAppListApi } from '@/api/uc/app'
import {
  sysConfigListApi,
  sysConfigAddApi,
  sysConfigEditApi,
  sysConfigDelApi,
  sysConfigBatchDelApi
} from '@/api/sys/config'
import { useTable } from '@/hooks/web/useTableTest'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const appData = ref<any>([])
let tabValue = ref('')
const getUcAppListApi = async () => {
  const res = await ucAppListApi({})
    .catch(() => {})
    .finally(() => {})
  if (res) {
    console.log('getUcAppListApi', res.data)
    appData.value = res.data
    tabValue.value = res.data[0].app_id
  }
}
getUcAppListApi()

const getSysConfigListApi = (pageData) => {
  // console.log('getSysConfigListApi', pageData)
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = sysConfigListApi({ ...pageData, app_id: tabValue.value })
  if (res) {
    loadingMain.close()
    return res
  }
}

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getSysConfigListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    width: 60,
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: false }
  },
  {
    field: 'code',
    label: '参数代码',
    width: 150,
    search: { show: true }
  },
  {
    field: 'name',
    label: '参数名称',
    width: 150,
    search: { show: true }
  },
  {
    field: 'type',
    label: '类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('sys_config_type', cellValue)
    },
    table: { show: true },
    search: { show: true, component: 'Select', componentProps: { options: dict.sys_config_type } },
    form: { show: true, component: 'Select', componentProps: { options: dict.sys_config_type } },
    detail: { show: true }
  },
  {
    field: 'value',
    label: '参数值'
  },
  {
    field: 'action',
    width: 300,
    fixed: 'right',
    label: '操作',
    form: { show: false },
    detail: { show: false }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const delLoading = ref(false)

const delData = async () => {
  const { getSelections } = methods
  const selections = await getSelections()
  const ids = selections.map((v: any) => v.app_id)
  delLoading.value = true
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await sysConfigBatchDelApi({ ids: ids.join(',') })
        .catch(() => {})
        .finally(() => {
          delLoading.value = false
        })
      if (res) {
        getList()
      }
    })
    .catch(() => {})
}

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (id) => {
  let delRes = await sysConfigDelApi({ id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          let res = await sysConfigEditApi({ ...data, app_id: tabValue.value })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })

      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any

          // app_id:tabValue.value
          let res = await sysConfigAddApi({ ...data, app_id: tabValue.value })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

const handleChange = () => {
  getList()
}
</script>

<template>
  <ContentWrap>
    <ElTabs v-model="tabValue" type="card" class="demo-tabs" @tab-change="handleChange">
      <ElTabPane
        :label="item.app_name"
        :name="item.app_id"
        v-for="(item, index) in appData"
        :key="index"
      />
    </ElTabs>

    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData()"> 批量删除 </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" :icon="iconEdit" @click="action('edit', row)" title="编辑">
          编辑
        </ElButton>
        <ElButton type="success" :icon="iconSee" @click="action('see', row)" title="详情">
          详情
        </ElButton>
        <ElButton type="danger" :icon="iconDel" @click="action('del', row)" title="删除">
          删除
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />
    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />
    <template #footer>
      <ElButton v-if="actionType !== 'see'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
